Extract Method

The Extract Method refactoring allows to turn a selected code fragment into a method.

To extract a code fragment into a method, first select it in the editor and invoke Refactoring | Extract Method or press Ctrl-Alt-E.

IDEA analyses the code and detects variables that are input for the selected code fragment and variables that are output for it. If there is exactly one output variable, it is used as a return value for the extracted method. In case there are multiple output variables, the Extract Method refactoring may not be applied and the error message is shown. There are a few possible solutions to allow the Extract Method work in this case. For example, you may introduce a special data-class which contains all output values. Because of great variety of such possibilities, the choice is left up to you and the Extract Method refactoring does not work with multiple output values in automatic mode, you must change your code before applying the refactoring.

The configuration dialog for the Extract Method refactoring consists of an edit field where you have to specify the name of the method, a parameter list and a text area with method signature preview.

All input variables are placed to the list of parameters and, by default, are passed to the extracted method as parameters. Unchecking the "Pass as Parameter" checkbox for any of the parameters will disable passing this value as a parameter. Instead, a local variable with "..." inital value is declared inside the extracted method. You have to fill the initializer with an appropriate value to make code compilable in this case.

You may reorder and rename parameters of the method as you want. To reorder the parameters use "Move up" and "Move down" buttons when the parameter is selected in the list. To rename a parameter, select it in the list and press the "Set name" button, or simply double-click the parameter.

After you have specified the name and parameters of the method, press the "OK" button. The new method is created

and the code fragment is replaced with a method call.

The code fragment to form the method may not necessary be a set of statements, it may also be an expression used somewhere in the code. For example, applying the Extract Method to

result in

Note: In addition to the case of multiple output variables, the Extract Method refactoring will not work in a few more cases. For example, it will not work for a code fragment which conditionally returns from the containing method and is not placed at the end of it.